import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/number_counter.dart';
import 'package:mall/components/product_price.dart';
import 'package:mall/core/models/business_condition.dart';
import 'package:mall/core/models/business_level.dart';
import 'package:mall/core/providers/pages/mine/manage/business_apply_model.dart';
import 'package:mall/core/providers/pages/mine/manage/business_condition_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/components/check_box.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/order/order_confirm_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class BusinessConditionPage extends StatelessWidget {
  static const routeName = '/BusinessConditionPage';
  final BusinessLevel args;

  BusinessConditionPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => BusinessConditionModel(context.read<NewApi>(), args),
      child: Scaffold(
        appBar: AppBar(
          title: Text('店铺购物'),
        ),
        body: _ViewStateWidget(),
      ),
    );
  }
}

class _ViewStateWidget extends StatelessWidget {
  const _ViewStateWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessConditionModel model = context.watch<BusinessConditionModel>();
    switch (model.viewState) {
      case ViewState.busy:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ViewState.error:
        return Center(
          child: Text(model.errorMessage),
        );
      case ViewState.success:
        return _SuccessWidget(
          businessCondition: model.businessCondition,
        );
      default:
        return Container();
    }
  }
}

class _SuccessWidget extends StatelessWidget {
  final BusinessCondition businessCondition;

  const _SuccessWidget({
    Key key,
    @required this.businessCondition,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => BusinessApplyModel(context.read<NewApi>(), businessCondition),
      child: Column(
        children: <Widget>[
          Expanded(
            child: _ListWidget(
              list: businessCondition.purchaseConditions,
            ),
          ),
          _BottomWidget(
            businessCondition: businessCondition,
          ),
        ],
      ),
    );
  }
}

/// 条件列表
class _ListWidget extends StatelessWidget {
  final List<PurchaseCondition> list;

  const _ListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        PurchaseCondition purchaseCondition = list[index];
        return Column(
          children: <Widget>[
            _ListItemHeaderWidget(
              data: purchaseCondition,
            ),
            _SubListWidget(
              list: purchaseCondition.productOptions,
            ),
            SizedBox(height: 7)
          ],
        );
      },
      itemCount: list.length,
    );
  }
}

/// 商品列表头部
class _ListItemHeaderWidget extends StatelessWidget {
  final PurchaseCondition data;

  const _ListItemHeaderWidget({
    Key key,
    @required this.data,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 12),
      height: 45,
      child: Text.rich(
        TextSpan(
          text: data.conditionName,
          style: TextStyle(fontSize: 17),
          children: [
            TextSpan(
              text: '   (需购满：${data.accountTypeTag}${data.needConsumeAmount})',
              style: TextStyle(fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
}

/// 商品列表
class _SubListWidget extends StatelessWidget {
  final List<ProductOption> list;

  const _SubListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            _SubListItemWidget(
              data: list[index],
              isLast: index == list.length - 1,
            ),
            Divider(height: 0.5),
          ],
        );
      },
      itemCount: list.length,
    );
  }
}

/// 商品
class _SubListItemWidget extends StatelessWidget {
  final ProductOption data;
  final bool isLast;

  const _SubListItemWidget({
    Key key,
    @required this.data,
    @required this.isLast,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessApplyModel model = context.watch<BusinessApplyModel>();
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: isLast
            ? BorderRadius.vertical(
                bottom: Radius.circular(10),
              )
            : BorderRadius.zero,
      ),
      height: 80,
      child: Row(
        children: <Widget>[
          CheckBoxWidget(
            checked: model.getCheckProductOption(data),
            onTap: (value) => model.setCheckProductOption(data, value),
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: ImageNetwork(
              url: '${data.productImageUrl}',
              width: 60,
              height: 60,
            ),
          ),
          SizedBox(width: 24),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  data.productModelName,
                  style: TextStyle(fontSize: 16),
                ),
                Row(
                  children: [
                    Expanded(
                      child: ProductPrice(list: data.priceVos),
                    ),
                    NumberCounter(
                      number: model.getQuantityProductOption(data),
                      updateValueChanged: (value) => model.setQuantityProductOption(data, value),
                    ),
                  ],
                )
              ],
            ),
          ),
          SizedBox(width: 12),
        ],
      ),
    );
  }
}

/// 底部
class _BottomWidget extends StatelessWidget {
  final BusinessCondition businessCondition;

  const _BottomWidget({
    Key key,
    @required this.businessCondition,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessApplyModel model = context.watch<BusinessApplyModel>();
    Map<String, double> totalJfbs = model.totalJfbs(model.businessCondition);
    return SafeArea(
      child: Container(
        color: Colors.white,
        height: 52,
        child: Row(
          children: <Widget>[
            CheckBoxWidget(
              checked: model.getCheckAll(businessCondition),
              onTap: (value) => model.setCheckAll(businessCondition, value),
            ),
            Expanded(
              child: Text('全选'),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text.rich(
                  TextSpan(
                    text: '合计：',
                    style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 14),
                    children: [
                      TextSpan(
                        text: '￥',
                        style: TextStyle(fontSize: 11),
                      ),
                      TextSpan(
                        text: '${model.getTotalPrice(businessCondition)}',
                        style: TextStyle(fontSize: 18),
                      ),
                      ...totalJfbs.entries.map(
                        (e) => TextSpan(
                          text: ' ${e.key}',
                          style: TextStyle(fontSize: 6),
                          children: [
                            TextSpan(
                              text: '${e.value.toInt()}',
                              style: TextStyle(fontSize: 12),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Text(
                  '不含运费',
                  style: TextStyle(color: Colors.grey, fontSize: 11),
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 8.w),
              child: model.viewState == ViewState.busy
                  ? RaisedButton(
                      onPressed: null,
                      elevation: 0,
                      child: SizedBox(width: 14, height: 14, child: CircularProgressIndicator()),
                    )
                  : RaisedButton(
                      onPressed: () => _onButtonClicked(context),
                      elevation: 0,
                      child: Text('结算(${model.getTotalQuantity(businessCondition)})'),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  void _onButtonClicked(BuildContext context) async {
    // 执行申请
    BusinessConditionModel businessConditionModel = Provider.of(context, listen: false);
    BusinessApplyModel businessApplyModel = Provider.of(context, listen: false);
    ViewState viewState = await businessApplyModel.businessApply(
      businessConditionModel.businessLevel,
      businessCondition,
    );
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(businessApplyModel.errorMessage);
        break;
      default:
        var cartIdQuantity = <int, int>{};
        businessApplyModel.list.forEach((value) {
          cartIdQuantity[value.cartId] = value.quantity;
        });
        Navigator.of(context).pushNamed(
          OrderConfirmScreen.routeName,
          arguments: OrderConfirmScreenArgs(cartIdQuantity),
        );
        break;
    }
  }
}
